package com.atguigu.gulimall.ware.config;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@EnableRabbit
@Configuration
@Slf4j
public class WareRabbitMQConfig {

    public static final String WARE_LOCKED_ROUTE_KEY_NAME = "ware.locked.ware";
    public static final String WARE_RELEASE_ROUTE_KEY_NAME = "ware.release.ware.#";
    public static final String WARE_EVENT_EXCHANGE_NAME = "ware-event-exchange";
    public static final String WARE_LOCKED_QUEUE_NAME = "ware.locked.ware.queue";
    public static final String WARE_RELEASE_QUEUE_NAME = "ware.release.ware.queue";
    public static final Long WARE_DELAY_QUEUE_TTL = 120_000L;

//    @RabbitListener(queues = WARE_RELEASE_QUEUE_NAME)
//    public void cancelOrder(Message message, Channel channel) {
//        log.info("receive message, {}, {}", message, channel);
//    }

    @Bean
    public Queue wareLockedQueue() {
        HashMap<String, Object> args = new HashMap<>();
        args.put("x-dead-letter-exchange", WARE_EVENT_EXCHANGE_NAME);
        args.put("x-dead-letter-routing-key", WARE_RELEASE_ROUTE_KEY_NAME.replace(".#", ""));
        args.put("x-message-ttl", WARE_DELAY_QUEUE_TTL);
        return new Queue(WARE_LOCKED_QUEUE_NAME, true, false, false, args);
    }

    @Bean
    public Queue wareReleaseQueue() {
        return new Queue(WARE_RELEASE_QUEUE_NAME, true, false, false, null);
    }

    @Bean
    public Binding wareLockedBinding() {
        return new Binding(WARE_LOCKED_QUEUE_NAME, Binding.DestinationType.QUEUE, WARE_EVENT_EXCHANGE_NAME, WARE_LOCKED_ROUTE_KEY_NAME, null);
    }

    @Bean
    public Binding wareReleaseBinding() {
        return new Binding(WARE_RELEASE_QUEUE_NAME, Binding.DestinationType.QUEUE, WARE_EVENT_EXCHANGE_NAME, WARE_RELEASE_ROUTE_KEY_NAME, null);
    }

    @Bean
    public Exchange wareEventExchange() {
        return new TopicExchange(WARE_EVENT_EXCHANGE_NAME, true, false);
    }


    @Bean
    public Jackson2JsonMessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }
}
